package com.dlg.commons.spring.fix.http;

import java.io.IOException;
import java.util.Locale;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.entity.DeflateDecompressingEntity;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.protocol.HttpContext;

/**
 * 修复响应内容编码
 * 
 * @author martin_duan@yeah.net
 * @since 2016-06-02
 *
 */
public class FixResponseContentEncoding implements HttpResponseInterceptor {

	public static final String UNCOMPRESSED = "http.client.response.uncompressed";

	public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
		final HttpEntity entity = response.getEntity();

		if (entity != null && entity.getContentLength() != 0) {
			final Header ceheader = entity.getContentEncoding();
			if (ceheader != null) {
				final HeaderElement[] codecs = ceheader.getElements();
				boolean uncompressed = false;
				for (final HeaderElement codec : codecs) {
					final String codecname = codec.getName().toLowerCase(Locale.ENGLISH);
					if ("gzip".equals(codecname) || "x-gzip".equals(codecname)) {
						response.setEntity(new GzipDecompressingEntity(response.getEntity()));
						uncompressed = true;
						break;
					} else if ("deflate".equals(codecname)) {
						response.setEntity(new DeflateDecompressingEntity(response.getEntity()));
						uncompressed = true;
						break;
					} else if ("identity".equals(codecname) || "plain".equalsIgnoreCase(codecname)) {
						return;
					} else {
						throw new HttpException("Unsupported Content-Coding: " + codec.getName());
					}
				}
				if (uncompressed) {
					response.removeHeaders("Content-Length");
					response.removeHeaders("Content-Encoding");
					response.removeHeaders("Content-MD5");
				}
			}
		}
	}
}
